<template>
  <div
    id="homechart2"
    class=" all-box"
  >
    <div class="chart-box-graph">
      <div class="chart-box">
        <div
          class="chart"
          ref="chart"
        ></div>
        <div
          class="all-btn"
          @click="getList()"
        >返回</div>
      </div>
    </div>
    <div class="graph-item-right">
      <div>
        <div>
          <div class="item-txt">学习进度</div>
          <div class="item-num">40.8%</div>
        </div>
        <div class="pie-box">40.8%</div>
      </div>
      <div>
        <div>
          <div class="item-txt">学习进度</div>
          <div class="item-num">40.8%</div>
        </div>
        <div class="pie-box">40.8%</div>
      </div>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";
export default {
  data() {
    return {
      chart: null,
      // colors: [
      //   "#5470C6",
      //   "#91CC75",
      //   "#FAC858",
      //   "#EE6666",
      //   "#73C0DE",
      //   "#3BA272",
      //   "#FC8452",
      //   "#9A60B4",
      //   "#ea7ccc",
      // ],
      colors: ["#9ddcfb", "#9dc3fb", "#abece2", "#dee8fb", "#f4f8cc"],

      data: {
        datas: [],
        links: [],
        categories: [],
      },
      option: {
        // backgroundColor: new this.$echarts.graphic.RadialGradient(
        //   0.3,
        //   0.3,
        //   0.8,
        //   [
        //     {
        //       offset: 0,
        //       color: "#f7f8fa",
        //     },
        //     {
        //       offset: 1,
        //       color: "#cdd0d5",
        //     },
        //   ]
        // ),
        // title: {
        //   text: "三国演义中人名出现次数排名",
        //   subtext: "ZBH",
        //   top: "top",
        //   left: "center",
        // },
        tooltip: {
          trigger: "item", // 根据你的需求设置触发方式
          formatter: function (params) {
            // 判断是否是线条（edge）
            if (params.dataType === "edge") {
              return null; // 如果是线条，则不显示 tooltip
            }
            // 使用 params.marker 保留颜色小球
            return `${params.marker} ${params.name}: <span style="color:${params.color};font-weight:bold;">${params.value}%</span>`;
          },
        },
        animationDuration: 3000,
        animationEasingUpdate: "quinticInOut",
        series: [
          {
            type: "graph",
            layout: "force",
            zoom: 2.5,
            // layout: 'circular',
            force: {
              repulsion: 200,
              //两点间的距离
              // edgeLength: 5,
              //中心力
              // gravity: 0.1,
              //斥力系数
              // repulsion: 50,
              //
              // layoutAnimation: false,
              //减缓移动
              // friction: 0.6,
            },

            data: [],
            links: [],
            categories: [],
            emphasis: {
              focus: "adjacency",
            },
            // focusNodeAdjacency: true,
            roam: true,
            // label: {
            //     show: true,
            //     position: "top",
            // },
            label: {
              show: true, // 显示标签
              position: "inside", // 将标签位置设为节点内部
              formatter: "{b}", // 使用节点名称作为标签文本
              fontSize: 14, // 根据需要调整字体大小
              color: "#000", // 根据需要调整字体颜色
            },
            lineStyle: {
              // color: "source",
              color: "#e0e7eb",
              curveness: 0,
              type: "solid",
            },
            // itemStyle: {
            //     // borderColor: "#04f2a7",
            //     // borderWidth: 6,
            //     // shadowBlur: 20,
            //     // shadowColor: "#04f2a7",
            //     color: function(params){
            //       const colors = ["#ff5722", "#4caf50", "#2196f3", "#9c27b0"];
            //       console.log(params,3334);
            //       const color = colors[params.data.value % colors.length];
            //       console.log(color,555);
            //       return color;
            //     },
            // },
          },
        ],
      },

      //测试数据
    };
  },
  mounted() {
    this.chartDom = this.$refs.chart;
    this.myChart = this.$echarts.init(this.chartDom);
    this.getList();
  },
  methods: {
    initColors() {
      const data = this.option.series[0].data;
      const colors = this.colors;
      data.forEach((item, index) => {
        // console.log(item, 32);
        item.itemStyle = {
          color: colors[item.nodeLevel - 1],
        };
      });
    },
    initSymbolSize() {
      const data = this.option.series[0].data;
      const levels = [100, 50, 30, 20];
      data.forEach((item, index) => {
        item.symbolSize = levels[item.nodeLevel - 1];
      });
    },
    initFontsize() {
      const data = this.option.series[0].data;
      const obj = data.find((item) => item.nodeLevel == 1);
      if (obj) {
        obj.label = {
          fontSize: 30,
        };
      }
    },
    initOption() {
      const series = this.option.series[0];
      series.data = this.data.datas;
      series.links = this.data.links;
      const categories = this.data.datas.map((item) => {
        return item.nodeLevel == 2;
      });
      series.categories = categories;
      this.initColors();
      this.initFontsize();
      this.initSymbolSize();
    },
    initChartGraph() {
      // this.chartDom = this.$refs.chart;
      // this.myChart = this.$echarts.init(this.chartDom);
      this.myChart.setOption(this.option);
      this.myChart.hideLoading();
      // 清空之前的点击事件监听器
      if (this.myChart) {
        this.myChart.off("click");
      }
      // 添加节点点击事件
      this.myChart.on("click", (params) => {
        // 判断是否点击的是节点
        if (params.dataType === "node") {
          // 获取点击的节点数据
          const clickedNode = params.data;
          console.log(clickedNode, 222);
          //attachBookId,nodeId
          this.getSubList(clickedNode.attachBookId, clickedNode.nodeId);
        }
      });
    },

    getList() {
      const url = "/dify/graph-relation";
      const params = {
        bookInfoId: 1, // 使用 params 传递查询参数
      };

      this.myChart.showLoading({
        text: "正在加载数据...",
        color: "#4cbbff",
        maskColor: "rgba(255, 255, 255, 0.8)",
        zlevel: 0,
      });

      this.$axios
        .get(url, {
          params, // 将参数传递给 `params` 属性
        })
        .then((response) => {
          const res = response;
          console.log(res, 1);
          if (res.code === 200) {
            console.log("成功获取数据1:", res.data);
            this.data = res.data;
            this.initOption();
            this.initChartGraph();
          } else {
            this.$message.error(res.msg || "获取列表失败，请稍后重试");
          }
        })
        .catch((error) => {
          this.$message.error(error.message || "获取列表失败，请稍后重试");
        });
    },
    getSubList(bookid, nodeId) {
      const url = "/dify/graph-relation-step";
      // 使用 params 传递查询参数
      const params = {
        bookId: bookid,
        nodeId: nodeId,
      };
      this.myChart.showLoading({
        text: "正在加载数据...",
        color: "#4cbbff",
        maskColor: "rgba(255, 255, 255, 0.8)",
        zlevel: 0,
      });
      this.$axios
        .get(url, {
          params, // 将参数传递给 `params` 属性
        })
        .then((response) => {
          const res = response;
          console.log(res, 1);
          if (res.code === 200) {
            console.log("成功获取数据2:", res.data);
            const isEmptyArray = (data) => data && data.length === 0;
            console.log(isEmptyArray(res.data), 333);
            if (isEmptyArray(res.data)) {
              this.myChart.hideLoading();
              this.$message.error(res.msg);
              return;
            }
            this.data = res.data;
            this.initOption();
            this.initChartGraph();
          } else {
            this.$message.error(res.msg || "获取列表失败，请稍后重试");
          }
        })
        .catch((error) => {
          this.$message.error(error.message || "获取列表失败，请稍后重试");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
#homechart2 {
  width: 100%;
  display: flex;
  .chart-box-graph {
    width: 100%;
    height: 670px;
    > div {
      position: relative;
      .chart {
        width: 100%;
        height: 670px;
      }
      .all-btn {
        position: absolute;
        top: 10px;
        left: 10px;
      }
    }
  }
  .graph-item-right {
    min-width: 237px;
    margin: 45px 45px 0 0;
    > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 237px;
      height: 103px;
      background: #ffffff;
      box-shadow: 5px 8px 27px 0px #b9caea;
      border-radius: 10px;
      padding: 0 23px 0;
      box-sizing: border-box;
      margin-bottom: 30px;
      .item-txt {
        font-weight: bold;
        font-size: 14px;
        color: #474747;
        margin-bottom: 8px;
      }
      .item-num {
        font-weight: bold;
        font-size: 25px;
        color: #2f7cdb;
      }
      .pie-box {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 74px;
        height: 74px;
        background: url("@/assets/img/home/pie.png") no-repeat 0 0;
        font-weight: bold;
        font-size: 14px;
        color: #ffffff;
      }
    }
  }
}
</style>